package com.sdb.common.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.sdb.common.config.AliPayConfig;
import com.sdb.common.entity.AliPay;
import com.sdb.fee.mapper.TdPayMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/alipay")
public class AliPayController {

    // 支付宝开放平台API的网关地址
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";

    // 数据格式
    private static final String FORMAT_JSON = "JSON";

    // 字符集编码
    private static final String CHARSET_UTF8 = "UTF-8";

    // 签名方式
    private static final String SIGN_TYPE_RSA2 = "RSA2";


    // 自定义配置类，用于读取支付宝相关配置信息
    @Autowired
    private AliPayConfig aliPayConfig;

    @Autowired
    private TdPayMapper tdPayMapper;

    /**
     * 发起支付请求的接口
     *
     * @param aliPay 包含支付信息的对象
     * @param httpResponse HTTP响应对象，用于返回支付表单
     * @throws Exception 可能抛出的异常
     */
    @GetMapping("/pay")
    public void pay(AliPay aliPay,
                    @RequestParam String totalAmount,  // 从前端接收金额
                    @RequestParam String returnUrl, // 从前端获取返回地址
                    @RequestParam String tradeNo, // 从前端获订单号
                    HttpServletResponse httpResponse) throws Exception {
        System.out.println("接收到的 returnUrl: " + returnUrl); // 添加此行
        // 创建默认的支付宝客户端实例
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT_JSON, CHARSET_UTF8, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE_RSA2);

        // 创建API对应的request
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        // 设置异步通知地址
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        // 设置同步跳转地址（支付完成后跳回前端页面，并携带成功状态）
//        String returnUrl = "http://localhost:8080/#/live/enter";
        request.setReturnUrl(returnUrl);
        // 替换原有的returnUrl设置
//        String returnUrl = "http://localhost:8080/#/live/enter"; // 或从前端获取动态地址
//        request.setReturnUrl(returnUrl);

        // 设置请求参数
        // 这里可以动态设置，例如从数据库或前端传入
//        aliPay.setTraceNo(UUID.randomUUID().toString().replaceAll("-", ""));
        aliPay.setTraceNo(tradeNo);
        aliPay.setTotalAmount(totalAmount);
        aliPay.setSubject("就诊卡缴费");

        // 构造业务请求参数
        request.setBizContent("{\"out_trade_no\":\"" + aliPay.getTraceNo() + "\","
                + "\"total_amount\":\"" + aliPay.getTotalAmount() + "\","
                + "\"subject\":\"" + aliPay.getSubject() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        // 请求支付宝接口
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        // 将表单直接输出到页面，用户点击后跳转到支付宝支付页面
        httpResponse.setContentType("text/html;charset=" + CHARSET_UTF8);
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    /**
     * 处理支付宝异步通知的接口
     *
     * @param request HTTP请求对象，包含支付宝返回的通知信息
     * @return 返回给支付宝的确认信息
     */
    @PostMapping("/notify")
    @ResponseBody
    public String payNotify(HttpServletRequest request) {
        // 检查交易状态是否为成功
        if ("TRADE_SUCCESS".equals(request.getParameter("trade_status"))) {
            System.out.println("=========支付宝异步回调========");

            // 存储所有请求参数
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            // 获取交易信息
            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            Double money = Double.valueOf(params.get("buyer_pay_amount"));


            // 打印交易信息
            System.out.println("交易名称: " + params.get("subject"));
            System.out.println("交易状态: " + params.get("trade_status"));
            System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
            System.out.println("商户订单号: " + params.get("out_trade_no"));
            System.out.println("交易金额: " + params.get("total_amount"));
            System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
            System.out.println("买家付款时间: " + params.get("gmt_payment"));
            System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));


            int payno = Integer.parseInt(tradeNo);
            // 更新支付状态
            tdPayMapper.updatestatus(payno);
            //获取就诊卡号
            String cardno = tdPayMapper.getcardno(payno);
            // 更新患者就诊卡余额
            tdPayMapper.updatemoney(money,cardno);
            // 更新记录余额
            tdPayMapper.updaterecord(money,payno);

        }

        // 告诉支付宝，异步通知已经收到
        return "success";
    }

}